package com.study.thirdpartyeventconsumer.controller.google;

import com.alibaba.fastjson.JSON;
import com.sun.mail.imap.IMAPFolder;
import org.joda.time.DateTime;
import org.testng.annotations.Test;

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import javax.mail.search.*;
import java.io.*;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

public class EmailReader {

    // 邮箱服务器配置
    private static final String IMAP_HOST = "imap.163.com";
    private static final String IMAP_PORT = "993";
    // 保存附件的根目录
    private static final String SAVE_PATH = "attachments";

    private String username;
    private String password;
    private Session session;

    public EmailReader() {
    }

    public EmailReader(String username, String password) {
        this.username = username;
        this.password = password;
        // 创建保存附件的目录
        createDirectory(SAVE_PATH);

        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imap.host", IMAP_HOST);
        props.setProperty("mail.imap.port", IMAP_PORT);

        props.setProperty("mail.imap.partialfetch", "false");
        props.setProperty("mail.imaps.partialfetch", "false");
        props.setProperty("mail.imap.ssl.enable", "true");
        session = Session.getInstance(props);
    }

    private void createDirectory(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public void readEmails() {


        try {
            Store store = session.getStore("imaps");
            store.connect(IMAP_HOST, username, password);

            System.out.println("连接成功，开始获取文件夹列表...");
            Folder[] list = store.getDefaultFolder().list();
            for (Folder folder : list) {
                System.out.println(folder.getName());
            }

            System.out.println("连接成功，开始读取邮件...");

            Folder inbox = store.getFolder("INBOX");
            IMAPFolder imapFolder = (IMAPFolder) inbox;
            imapFolder.doCommand(p -> {
                p.id("a");
                return null;
            });
            inbox.open(Folder.READ_ONLY);

              // 固定拉取一周内的数据
            Date date = new DateTime(new Date()).minusDays(500).toDate();
            SearchTerm receivedDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, date);
            SearchTerm sentDateTerm = new SentDateTerm(ComparisonTerm.GE, date);
            AndTerm andTerm = new AndTerm(receivedDateTerm, sentDateTerm);
            Message[] messages = inbox.search(andTerm);
            System.out.println("总邮件数: " + messages.length);

//            for (int i = 0; i < messages.length; i++) {
//                System.out.println("\n=====第 " + (i + 1) + " 封邮件=====");
//                processMessage(messages[i]);
//            }
//            System.out.println("获取uid：" + ((UIDFolder) inbox).getUID(messages[messages.length - 1]));
//            processMessage(messages[messages.length - 1]);


            inbox.close(false);
            store.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processMessage(Message message) throws Exception {
        // 打印基本信息
        System.out.println("发件人: " + getFrom(message));
        System.out.println("主题: " + getSubject(message));
        System.out.println("发送时间: " + message.getSentDate());
        System.out.println("邮件的唯一ID值：" + message.getHeader("Message-ID")[0]);
          Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
        System.out.println("<UNK>: " + toAddresses[0].toString());
        // 处理邮件内容
        processContent(message);
    }

    /**
     * 根据邮件唯一 ID 彻底删除邮件（硬删除）
     *
     * @param messageId 邮件的唯一 ID
     * @throws MessagingException 如果操作失败
     */
    public void deletePermanentlyById(long messageId) throws MessagingException {
        Store store = null;
        Folder folder = null;

        try {
            store = session.getStore("imaps");
            store.connect(IMAP_HOST, username, password);

            // 打开邮件所在的文件夹（例如 INBOX）
            folder = store.getFolder("INBOX");
            IMAPFolder imapFolder = (IMAPFolder) folder;
            imapFolder.doCommand(p -> {
                p.id("a");
                return null;
            });
            if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }

            // 根据邮件 ID 查找邮件
            Message message = ((UIDFolder) folder).getMessageByUID(messageId);
            if (message == null) {
                throw new MessagingException("未找到邮件 ID: " + messageId);
            }

            // 标记邮件为删除
            message.setFlag(Flags.Flag.DELETED, true);

            // 提交删除操作
            folder.expunge();

            System.out.println("邮件已彻底删除");
        } finally {
            // 关闭文件夹和连接
            if (folder != null && folder.isOpen()) {
                folder.close(true); // 提交删除操作
            }
            if (store != null) {
                store.close();
            }
        }
    }

    private void processContent(Part part) throws Exception {

        if (part.isMimeType("text/plain")) {
//            // 处理纯文本
//            System.out.println("文本内容：");
//            System.out.println(part.getContent());
        } else if (part.isMimeType("text/html")) {
            // 处理HTML内容
            System.out.println("HTML内容：");
            System.out.println(part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            // 处理多部分邮件
            Multipart multipart = (Multipart) part.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                processContent(multipart.getBodyPart(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            // 处理邮件
            processContent((Part) part.getContent());
        } else {
            // 处理附件
            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) ||
                    Part.INLINE.equalsIgnoreCase(part.getDisposition()) ||
                    (part.getDisposition() == null && part.getFileName() != null)) {
                saveAttachment(part);
            }
        }
    }

    private void saveAttachment(Part part) throws Exception {
        String fileName = part.getFileName();
        System.out.println("文件名："+fileName);
        String[] cids = part.getHeader("Content-ID");
        System.out.println(cids[0]);
        if (fileName == null) {
            fileName = UUID.randomUUID() + getFileExtension(part.getContentType());
        } else {
            fileName = MimeUtility.decodeText(fileName);
        }

        // 创建子文件夹，按照文件类型分类
        String subFolder = getSubFolderByContentType(part.getContentType());
        String fullPath = SAVE_PATH + File.separator + subFolder;
        createDirectory(fullPath);

        // 保存文件
        String filePath = fullPath + File.separator + fileName;
//        System.out.println(part.getHeader("Content-ID")[0]);
        System.out.println("保存附件: " + filePath);
        OutputStream fos = new BufferedOutputStream(new FileOutputStream(filePath), 8192);
        part.writeTo(fos);
        fos.close();
    }

    private String getSubFolderByContentType(String contentType) {
        contentType = contentType.toLowerCase();
        if (contentType.contains("image")) {
            return "images";
        } else if (contentType.contains("video")) {
            return "videos";
        } else if (contentType.contains("audio")) {
            return "audios";
        } else {
            return "others";
        }
    }

    private String getFileExtension(String contentType) {
        if (contentType.contains("jpeg") || contentType.contains("jpg")) return ".jpg";
        if (contentType.contains("png")) return ".png";
        if (contentType.contains("gif")) return ".gif";
        if (contentType.contains("pdf")) return ".pdf";
        if (contentType.contains("mp4")) return ".mp4";
        if (contentType.contains("mp3")) return ".mp3";
        return "";
    }

    private String getFrom(Message message) throws MessagingException {
        Address[] froms = message.getFrom();
        if (froms != null && froms.length > 0) {
            return decodeText(froms[0].toString());
        }
        return null;
    }

    private String getSubject(Message message) throws MessagingException {
        String subject = message.getSubject();
        return subject != null ? decodeText(subject) : null;
    }

    private String decodeText(String text) {
        try {
            return MimeUtility.decodeText(text);
        } catch (Exception e) {
            return text;
        }
    }

}
